package com.zn.kjj.util.shiro;

import java.util.*;

import com.zn.kjj.entity.SysLogin;
import com.zn.kjj.service.SysLoginable;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;


/**
 * shiro身份校验核心类
 * @author Administrator
 */

public class PreShiroRealm extends AuthorizingRealm {
	//用户登录次数计数  redisKey 前缀
	private String SHIRO_LOGIN_COUNT = "shiro_login_count_";
	//用户登录是否被锁定    一小时 redisKey 前缀
	private String SHIRO_IS_LOCK = "shiro_is_lock_";
	private static final String USER_DISABLE = "0";
	@Autowired
	@Qualifier("sysLoginImpl")
	private SysLoginable sysLoginImpl;
	/**
	 * 认证信息.(身份验证) : Authentication 是用来验证用户身份
	 * @param authcToken
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String name = token.getUsername();
		String password = String.valueOf(token.getPassword());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("nickname", name);
		String paw = password+name;
		map.put("pswd", paw);
		System.out.println(name+"   "+paw);
		SysLogin user = sysLoginImpl.selectByLoginName(name);
		if (null == user) {
			throw new AccountException("帐号或密码不正确！");
		}else if(USER_DISABLE.equals(user.getIsEnable())){
			throw new DisabledAccountException("此帐号已经设置为禁止登录！");
		}else{
			user.setLastTime(new Date().toString());
			int nType = sysLoginImpl.updateByPrimaryKeySelective(user);
			Logger.getLogger(getClass()).debug("更新用户登录时间返回表示type=" + nType);
		}
		Logger.getLogger(getClass()).info("身份认证成功，登录用户："+name);
		return new SimpleAuthenticationInfo(user.getLoginName(), user.getLoginPass(), getName());
	}

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		System.out.println("权限认证方法：PreShiroRealm.doGetAuthorizationInfo()");
		SysLogin user = (SysLogin)SecurityUtils.getSubject().getPrincipal();
		String userId = user.getGuid();
		SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
		//根据用户ID查询角色（role），放入到Authorization里。
		/*Map<String, Object> map = new HashMap<String, Object>();
		map.put("user_id", userId);
		List<SysRole> roleList = sysRoleService.selectByMap(map);
		Set<String> roleSet = new HashSet<String>();
		for(SysRole role : roleList){
			roleSet.add(role.getType());
		}*/
		Set<String> roleSet = new HashSet<String>();
		roleSet.add("100002");
		info.setRoles(roleSet);
		//根据用户ID查询权限（permission），放入到Authorization里。
		/*List<SysPermission> permissionList = sysPermissionService.selectByMap(map);
		Set<String> permissionSet = new HashSet<String>();
		for(SysPermission Permission : permissionList){
			permissionSet.add(Permission.getName());
		}*/
		Set<String> permissionSet = new HashSet<String>();
		permissionSet.add("权限添加");
		permissionSet.add("权限删除");
		info.setStringPermissions(permissionSet);
        return info;
	}
}
